//
//  LBFileDownloadHelper.m
//  ZhToMeow
//
//  Created by JackYoung on 2020/4/9.
//  Copyright © 2020 Meow. All rights reserved.
//

#import "LBFileDownloadHelper.h"
#define FileDownloadDirectoryName "FileDownloadDirectoryName"

@interface LBFileDownloadHelper()

@property(nonatomic, strong) NSOperationQueue *downloadQueue;

@end

@implementation LBFileDownloadHelper

- (instancetype)init {
    if ([super init]) {
        _downloadQueue = [NSOperationQueue new];
        _downloadQueue.maxConcurrentOperationCount = 8;
    }
    return self;
}

- (void)downloadFileWithFileName:(NSString *)fileUrl completionBlock:(void (^)(NSString *localFilePath))completionBlock failureBlock:(void (^)(NSError * _Nullable))failureBlock{
    if ([fileUrl hasPrefix:@"http://"] || [fileUrl hasPrefix:@"https://"]) {
        [self parseWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:fileUrl] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120.0] fileUrl:fileUrl completionBlock:completionBlock failureBlock:failureBlock];
    }
}

- (void)parseWithURLRequest:(NSURLRequest *)URLRequest fileUrl: (NSString *)fileUrl completionBlock:(void (^)(NSString *localFilePath))completionBlock failureBlock:(void (^)(NSError * _Nullable))failureBlock {
    
    NSString *localFilePath = [NSString stringWithFormat:@"%@/%@.%@",[self cacheDirectory:[self cacheKey:URLRequest.URL]],[self cacheKey:URLRequest.URL],[self getExtensionByFileUrl:fileUrl]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePath]) {
        completionBlock(localFilePath);
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[[NSURLSession sharedSession] dataTaskWithRequest:URLRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil && data != nil) {
                [self parseWithData:data cacheKey:[self cacheKey:URLRequest.URL] fileUrl:fileUrl completionBlock:completionBlock failureBlock:failureBlock];
            } else {
                if (failureBlock) {
                    failureBlock(error);
                }
            }
        }] resume];
    });
}

- (void)parseWithData:(nonnull NSData *)data
             cacheKey:(nonnull NSString *)cacheKey
              fileUrl: (NSString *)fileUrl
      completionBlock:(void (^)(NSString *localFilePath))completionBlock
         failureBlock:(void ( ^ _Nullable)(NSError * _Nonnull error))failureBlock {
    
    if (!data || data.length < 4) {
        return;
    }
    
    if (data != nil) {
        NSString *cacheDir = [self cacheDirectory:cacheKey];
        if ([cacheDir isKindOfClass:[NSString class]]) {
            BOOL flag = [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:nil];
            if (flag) {
                NSLog(@"flag true");
            }
        }
        NSString *tmpPath = [cacheDir stringByAppendingFormat:@"/%@.%@", cacheKey,[self getExtensionByFileUrl:fileUrl]];
        [data writeToFile:tmpPath atomically:YES];
        if (completionBlock) {
            completionBlock(tmpPath);
        }
    }
    return;
}

- (NSString *)getExtensionByFileUrl:(NSString *)fileUrl {
    NSArray *stringParts = [fileUrl componentsSeparatedByString:@"."];
    NSString *extension = [stringParts lastObject];
    if (extension != nil) {
        return extension;
    }
    return @"";
}

- (nonnull NSString *)cacheKey:(NSURL *)url {
    return [url.absoluteString xh_md5String];
}

- (nullable NSString *)cacheDirectory:(NSString *)cacheKey {
    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [cacheDir stringByAppendingFormat:@"/%s/%@", FileDownloadDirectoryName,cacheKey];
}


@end
